package com.cosytek.farmmanager.autoupgrade;

import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

/**
 * Created by Happy on 2015/1/27.
 */
public class UpdateCheck {
    public interface UpdateCheckListener {
        public void onUpdateCheckCompleted(UpdateInfo updateInfo);
    }

    private final static String TAG = "UpdateCheck";
    private String mResult;
    private final String mUpdateUrl;
    private final UpdateCheckListener mListener;
    private CheckUpdateTask mTask;

    public UpdateCheck(String updateUrl, UpdateCheckListener listener) {
        mUpdateUrl = updateUrl;
        mListener = listener;
    }

    public void start() {
        if (mTask != null) {
            Log.e(TAG, "update check is already start");
            return;
        }

        mTask = new CheckUpdateTask();
        mTask.execute((Void) null);
    }

    private class CheckUpdateTask extends AsyncTask<Void, Void, Boolean> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);

            if (!aBoolean) {
                onFailed();
                return;
            }

            UpdateInfo info = null;

            if (mResult != null) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(mResult);
                    info = UpdateInfo.fromJSON(jsonObject);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            onSucceed(info);
        }

        @Override
        protected Boolean doInBackground(Void... voids) {
            HttpGet request = new HttpGet(mUpdateUrl);
            AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
            try {
                HttpResponse resp = client.execute(request);
                HttpEntity entity = resp.getEntity();
                if (entity == null) {
                    Log.e(TAG, "http response entity is null");
                    return false;
                }

                mResult = EntityUtils.toString(entity, "UTF-8");
                Log.e(TAG, "succeed get update json:" + mResult);
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                client.close();
            }
            return false;
        }
    }

    private void onSucceed(UpdateInfo info) {
        mListener.onUpdateCheckCompleted(info);
    }

    private void onFailed() {
        mListener.onUpdateCheckCompleted(null);
    }
}
